//
//  WCTextFileWindowController.m
//  WabbitCode
//
//  Created by William Towe on 4/19/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCTextFileWindowController.h"
#import "WCInterfacePerformer.h"
#import "WCTextFile.h"
#import "WCProject.h"
#import "WCUnsavedFilesWindowController.h"
#import "WCBasicPerformer.h"
#import "NSTextView+WCExtensions.h"
#import "WCSymbol.h"


@implementation WCTextFileWindowController
- (void)dealloc {
	[_textFile release];
	[_textView release];
	[super dealloc];
}

- (void)windowDidLoad {
	[super windowDidLoad];
	
	[[self window] setFrameFromString:[[self textFile] separateEditorWindowFrameString]];
	
	NSScrollView *scrollView = [[WCInterfacePerformer sharedInstance] scrollViewWithTextViewForTextFile:_textFile inProject:[self project]];
	[self willChangeValueForKey:@"textView"];
	_textView = [[scrollView documentView] retain];
	[self didChangeValueForKey:@"textView"];
	[scrollView setFrame:[_dummyView frame]];
	[[[self window] contentView] replaceSubview:_dummyView with:scrollView];
	[[[self project] openTextFiles] addObject:[self textFile]];
	
	[[self textView] setSelectedRangeSafely:[[self textFile] fileSelectedRange]];
	
	NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier:@"WCTextFileWindowToolbar"] autorelease];
	
	// turn on autosaving for release builds
#ifndef WCDEBUG
	[toolbar setAutosavesConfiguration:YES];
#endif
	[toolbar setDisplayMode:NSToolbarDisplayModeDefault];
	[toolbar setSizeMode:NSToolbarSizeModeRegular];
	[toolbar setAllowsUserCustomization:YES];
	[toolbar setDelegate:self];
	[[self window] setToolbar:toolbar];
	
	[_projectBuildStatusTextField bind:@"imagesAndStrings" toObject:[self project] withKeyPath:@"buildStatusImagesAndStrings" options:nil];
	[_actionPopUpButton setMenu:[[WCInterfacePerformer sharedInstance] menuForProjectTextViewActionButton]];
}

- (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName {
	[[self window] setRepresentedFilename:[[self textFile] absoluteFilePath]];
	return [NSString stringWithFormat:NSLocalizedString(@"%@ - %@",@"window title for text file window"), [[self textFile] name], [displayName stringByDeletingPathExtension]];
}

- (void)windowDidMove:(NSNotification *)note {
	[[self textFile] setSeparateEditorWindowFrameString:[[self window] stringWithSavedFrame]];
}

- (void)windowDidResize:(NSNotification *)note {
	[[self textFile] setSeparateEditorWindowFrameString:[[self window] stringWithSavedFrame]];
}

- (BOOL)windowShouldClose:(id)window {
	WCTextFile *textFile = [self textFile];
	
	if ([[[self project] openTextFiles] countForObject:textFile] > 1)
		return YES;
	// if the file hasn't been edited, close it without confirmation
	else if (![textFile isEdited])
		return YES;
	
	NSInteger result = [WCUnsavedFilesWindowController runModalForUnsavedFiles:[NSArray arrayWithObject:textFile] type:WCUnsavedFilesTypeBeforeClosingFile];
	
	if (result == NSCancelButton)
		return NO;
	return YES;
}

- (void)windowWillClose:(NSNotification *)note {
	[[[self textFile] fileTextStorage] removeLayoutManager:[_textView layoutManager]];
	if ([[[self project] openTextFiles] countForObject:[self textFile]] == 1)
		[[self textFile] resetTextFile];
	[[[self project] openTextFiles] removeObject:[self textFile]];
}

- (NSInteger)numberOfItemsInMenu:(NSMenu *)menu {
	NSUInteger count = [[self textFile] numberOfFileSymbols];
	return (!count)?2:++count;
}

- (BOOL)menu:(NSMenu *)menu updateItem:(NSMenuItem *)item atIndex:(NSInteger)index shouldCancel:(BOOL)shouldCancel {
	NSUInteger count = [[self textFile] numberOfFileSymbols];
	[item setTarget:self];
	[item setAction:@selector(_textViewSymbolsPopUpButtonAction:)];
	if (!count) {
		if (!index) {
			[item setHidden:YES];
			[item setImage:[NSImage imageNamed:NSImageNameListViewTemplate]];
		}
		else {
			[item setTitle:NSLocalizedString(@"No Symbols",@"No Symbols")];
		}
	}
	else {
		if (!index) {
			[item setHidden:YES];
			[item setImage:[NSImage imageNamed:NSImageNameListViewTemplate]];
		}
		else {
			WCSymbol *symbol = [[[self textFile] fileSymbolsArray] objectAtIndex:--index];
			[item setTitle:[NSString stringWithFormat:@"%@ - Line: %u",[symbol name],[symbol lineNumber]+1]];
			[item setImage:[symbol icon]];
			[item setRepresentedObject:symbol];
		}
	}
	return YES;
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)identifier willBeInsertedIntoToolbar:(BOOL)flag {
	NSToolbarItem *item = [[WCBasicPerformer sharedInstance] toolbarItemForItemIdentifier:identifier inProject:[self project]];
	
	return item;
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar {
	return [NSArray arrayWithObjects:kWCProjectToolbarProjectOverviewIdentifier, kWCProjectToolbarBuildIdentifier,kWCProjectToolbarCountCodeIdentifier,kWCProjectToolbarBuildResultsWindowIdentifier,kWCProjectToolbarFindInProjectWindowIdentifier,kWCProjectToolbarProjectWindowIdentifier, NSToolbarSpaceItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, nil];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar {
	return [NSArray arrayWithObjects:kWCProjectToolbarProjectOverviewIdentifier,NSToolbarSpaceItemIdentifier,kWCProjectToolbarCountCodeIdentifier,NSToolbarSpaceItemIdentifier,kWCProjectToolbarBuildIdentifier,NSToolbarFlexibleSpaceItemIdentifier,kWCProjectToolbarBuildResultsWindowIdentifier,kWCProjectToolbarFindInProjectWindowIdentifier,kWCProjectToolbarProjectWindowIdentifier, nil];
}

- (id)initWithTextFile:(WCTextFile *)textFile; {
	if (!(self = [super initWithWindowNibName:@"WCTextFileWindow"]))
		return nil;
	
	_textFile = [textFile retain];
	
	return self;
}

+ (WCTextFileWindowController *)textFileWindowWithTextFile:(WCTextFile *)textFile; {
	return [[[[self class] alloc] initWithTextFile:textFile] autorelease];
}

@synthesize textFile=_textFile,textView=_textView;

@dynamic project;
- (WCProject *)project {
	return (WCProject *)[self document];
}

- (IBAction)_textViewSymbolsPopUpButtonAction:(id)sender {
	WCSymbol *symbol = [sender representedObject];
	
	WCTextView *tv = [self textView];
	NSString *string = [tv string];
	NSRange range = [string lineRangeForRange:NSMakeRange([[symbol textFile] lineStartIndexForLineNumber:[symbol lineNumber]], 0)];
	
	range = [string rangeOfString:[symbol name] options:NSLiteralSearch range:range];
	
	[tv setSelectedRange:range];
	[tv scrollRangeToVisible:[tv selectedRange]];
	[tv showFindIndicatorForRange:[tv selectedRange]];
}
@end
